<?php
/**
 * 转盘抽奖模型
 */
namespace Common\Model;

class TurnModel extends BaseModel{

    //大转盘抽奖奖品发货状态
    const PRIZE_ACCEPT_STATUS_DEFAULT    =1;//默认发货
    const PRIZE_ACCEPT_STATUS_DID        =2;//已发货
    const PRIZE_ACCEPT_STATUS_NO         =3;//未发货


    const GOTWAY_NEW                = 'NEW';//新用户
    const GOTWAY_APPLY              = 'APPLY';//报名
    const GOTWAY_SIGN               = 'SIGN';//签到
    const GOTWAY_BABYBIRTHDAY       = 'BABY_BIRTHDAY';//宝贝生日

    //大转盘概率基数
    const LUCKY_RATE_SUM        = 100000;

    /**
     * @return array
     */
    public static function getGotWayKv(){
        return array(
            self::GOTWAY_NEW            => '新用户',
            self::GOTWAY_APPLY          => '报名',
            self::GOTWAY_SIGN           => '签到',
            self::GOTWAY_BABYBIRTHDAY   => '宝贝生日'
        );
    }


    private static $setinstance=null;
    public static function getSetInstance(){
        if(!self::$setinstance){
            self::$setinstance=M('turn_set',null,DB_MAIN_CFG);
        }
        return self::$setinstance;
    }


    private static $iteminstance=null;
    public static function getItemInstance(){
        if(!self::$iteminstance){
            self::$iteminstance=M('turn_item',null,DB_MAIN_CFG);
        }
        return self::$iteminstance;
    }

    private static $mappinginstance=null;
    public static function getMappingInstance(){
        if(!self::$mappinginstance){
            self::$mappinginstance=M('turn_active_mapping',null,DB_MAIN_CFG);
        }
        return self::$mappinginstance;
    }

    private static $joinInstance=null;
    public static function getJoinInstance(){
        if(!self::$joinInstance){
            self::$joinInstance=M('turn_join',null,DB_MAIN_CFG);
        }
        return self::$joinInstance;
    }

    private static $chanceInstance=null;
    public static function getChanceInstance(){
        if(!self::$chanceInstance){
            self::$chanceInstance=M('turn_chance',null,DB_MAIN_CFG);
        }
        return self::$chanceInstance;
    }



    /**
     * 转盘活动列表
     * @param $page
     * @param $pageSize
     * @param $beginDate
     * @param $endDate
     * @param $title
     * @return array
     */
    public static function getTurnList($page,$pageSize,$beginDate,$endDate,$title){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        $where = ' 1  ';
        if ($beginDate){
            $startTimestamp=strtotime($beginDate);
            $where .=" and  addTime >=".$startTimestamp;
        }
        if ($endDate){
            $endTimestamp=strtotime($endDate);
            $where .=" and  addTime <".($endTimestamp+UtilsModel::ONE_DAY);
        }
        if ($title){
            $where .= " and  title like '%{$title}%'";
        }

        $dataSuccess['total'] = self::getSetInstance()->where($where)->count();//获取数据总条数
        $dataSuccess['page'] = max($page,1);//返回当前页
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;

        $list = self::getSetInstance()
             ->where($where)
             ->limit($offset,$pageSize)
             ->select();
        $dataSuccess['data'] = $list;
        return $dataSuccess;
    }


    public static function getMappingList($page,$pageSize,$beginDate,$endDate,$turn=0){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        $where = ' 1 ';
        if ($beginDate){
            $where .=" and  applyStartTime >=".$beginDate;
        }

        if ($endDate){
            $where .=" and  applyStartTime <=".$endDate .' 59:59:59';
        }

        if ($turn>0){
            $where .= ' and  turn = '.$turn;
        }

        $dataSuccess['total'] = self::getMappingInstance()->where($where)->count();//获取数据总条数
        $dataSuccess['page'] = max($page,1);//返回当前页
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;

        $list = self::getMappingInstance()
            ->where($where)
            ->limit($offset,$pageSize)
            ->select();
        $dataSuccess['data'] = $list;


        return $dataSuccess;
    }












    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////








    
    /**
     * @param $uid 用户编号 
     * @param $setId 大转盘编号
     * @return mixed
     */
    public static function readLuckyPrizeSet($uid,$setId){
        $luckyM     = self::getItemInstance();
        $luckyLogM  = self::getJoinInstance();

        $data = $luckyM->where("setId={$setId}")->select();
        $empty=array();
        foreach ($data as $k=>$v){
            if ($v['prizeType']==0){//谢谢参与提取出来
                $empty[]=$k;
            }
        }


        //调整中奖率
        foreach($data as $key => $val){
            if(floatval($val['hitRate']) > 0){
                if($val['prizeNum'] == 0){//奖品剩余数量
                    $index=array_rand($empty,1);
                    $emptyPos=$empty[$index];
                    $data[$emptyPos]['hitRate'] += floatval($data[$key]['hitRate']);

                    $data[$key]['hitRate'] = 0;
                    $luckyM->where("id={$data[$key]['id']}")->setField('hitRate',$data[$key]['hitRate']);
                    $luckyM->where("id={$data[$emptyPos]['id']}")->setField('hitRate',$data[$emptyPos]['hitRate']);
                }else if($val['dayLimitTimes'] > 0){//日限制
                    $t = time();
                    $start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
                    $end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));
                    $dayTimes = $luckyLogM->where("prizeID = {$val['id']} && uid={$uid} && addTime between {$start} and {$end}")->count();
                    if($dayTimes >= $val['dayLimitTimes']){
                        $index=array_rand($empty,1);
                        $emptyPos=$empty[$index];
                        $data[$emptyPos]['hitRate'] += floatval($data[$key]['hitRate']);
                        $data[$key]['hitRate'] = 0;
                    }
                } else if($val['allLimitTimes'] > 0){//总限制
                    $allTimes = $luckyLogM->where("prizeID = {$val['id']} && uid={$uid}")->count();
                    if($allTimes > $val['allLimitTimes']){
                        $index=array_rand($empty,1);
                        $emptyPos=$empty[$index];
                        $data[$emptyPos]['hitRate'] += floatval($data[$key]['hitRate']);
                        $data[$key]['hitRate'] = 0;
                    }
                }
            }
        }
        return $data;
    }



    private static function  orderbyRate($a,$b){
        if ($a['hitRate']==$b['hitRate']) return 0;
        return ($a['hitRate']<$b['hitRate'])?-1:1;
    }





    /**
     * 得到大转盘结果
     * @param $uid
     * @param int $turn  转盘编号
     * @param int $pointFee 积分费用
     * @return array
     */
    public static function getLuckyResult($uid,$mappingId,$turn,$active){
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        $sum = self::LUCKY_RATE_SUM;
        $num = rand(1,$sum);


        $luckySet = self::readLuckyPrizeSet($uid,$turn);

        $hitData = array();
        $minNum = intval(0); $maxNum = intval(0);
        foreach($luckySet as $key => $value){
            if($key>0){$minNum = $maxNum;}
            $maxNum += $value['hitRate']*$sum;
            if($num>$minNum && $num <= $maxNum){
                $hitData['prizeID']     = $value['id'];
                $hitData['val']         = $value['extra'];
                $hitData['prizeType']   = $value['prizeType'];
                $hitData['prizeName']   = $value['prizeName'];
                break;
            }
        }
        if(!$hitData){
            //抽奖结果为空集
            $dataFailure['msg'] = "抽奖失败，请重新抽奖";
            return $dataFailure;
        } else{
            $result=self::saveUserLuckyLog($mappingId,$turn,$active,$uid,$hitData['prizeID'],$hitData['prizeName'],$hitData['val'],$hitData['prizeType']);
            return $result;
        }
    }



    /**
     * 保存用户大转盘抽奖记录
     * @param $uid
     * @param $prizeId
     * @param $prizeName
     * @param $val
     * @param $prizeType
     * @return array
     */
    public static function saveUserLuckyLog($mid,$turn,$active,$uid,$prizeId,$prizeName,$val,$prizeType){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$uid){
            return $dataFailure;
        }
        $time = time();
        $uInfo = M('u_user_base',null,DB_MAIN_CFG)->where("uid={$uid}")->field('realName,bindPhone,province,city,district,address')->find();
        $data = array(
            'mid'       =>$mid,
            'turn'      =>$turn,
            'active'    =>$active,
            'uid'       =>$uid,
            'realName'  =>$uInfo['realName'],
            'bindPhone' =>$uInfo['bindPhone'],
            'prizeID'   =>$prizeId,
            'prizeType' =>$prizeType,
            'prizeNote' =>$prizeName,
            'addTime'   =>$time
        );
        if($prizeType == ELEMENT_TYPE_ENTITY){
            $data['status'] = self::PRIZE_ACCEPT_STATUS_NO;
        } else{
            $data['status'] = self::PRIZE_ACCEPT_STATUS_DEFAULT;
        }
        self::getJoinInstance()->startTrans();

            //积分抽奖 抽奖消耗积分和中奖积分加减
            if($prizeType == ELEMENT_TYPE_POINT){
                UserModel::plusPoint($uid,-1,$val,OPT_TURN);
                $data['prizeNote']="获得{$val}积分";
            }
            elseif($prizeType == ELEMENT_TYPE_EXP){
                UserModel::plusEXP($uid,$val,OPT_TURN);
                $data['prizeNote']="获得{$val}经验";
            }
            elseif($prizeType == ELEMENT_TYPE_ENTITY){
                //抽中实物，判断用户收获地址是否填写完整
                if($uInfo['province'] && $uInfo['city'] && $uInfo['district'] && $uInfo['address']){
                    $dataSuccess['address'] = 0;
                } else{
                    $dataSuccess['address'] = 1;
                }
                $dataSuccess['msg']     = $prizeName;
                $dataSuccess['note']    = $prizeName;
                $data['prizeNote']      = $prizeName;
            }
            elseif($prizeType  == ELEMENT_TYPE_ECOUPONS){//异业券
                //获取异页券号 并更新异页券列表信息
                $code = SignLuckyModel::getCodeAndUpdate($uid,$val);
                if($code['status']==1){
                    //卡券号获取失败，请联系管理员
                    $data['prizeNote'] = $prizeName."<br/>券号：卡券号获取失败，请联系管理员";
                } else{
                    $data['prizeNote'] = $prizeName."<br/>券号：".$code['msg'];
                }
            }
            elseif($prizeType == ELEMENT_TYPE_CARD){//卡券
                $code = CouponModel::sendCard_both($val,$uid,OBJ_TYPE_LUCKY);
                if($code['status']==1){
                    //卡券号获取失败，请联系管理员
                    $data['prizeNote'] = $prizeName."<br/>券号：卡券号获取失败，请联系管理员";
                } else{
                    $data['prizeNote'] = $prizeName."<br/>券号：".$code['code'];
                }
            }
            elseif($prizeType ==ELEMENT_TYPE_MONEY){//现金红包
                $data['prizeNote'] = "获得{$prizeName}";
                $openid=session('openid');
                $result=WeixinRedPackModel::sendPack($openid,$val*100,"大转盘抽奖","恭喜发财，万事如意");
                if (strcasecmp($result,'success')!=0){
                    self::getJoinInstance()->rollback();
                    $dataFailure['msg'] = "抽奖失败，请联系管理员";
                    return $dataFailure;
                }
                
            }
            elseif($prizeType == ELEMENT_TYPE_CHANCE){
                $data['prizeNote'] = "获得{$prizeName}";
            }
            elseif($prizeType == 0){
                $data['prizeNote'] = "谢谢参与";
            }
            else{
                self::getJoinInstance()->rollback();
                $dataFailure['msg'] = "抽奖失败，请联系管理员";
                return $dataFailure;
            }

        $addId = self::getJoinInstance()->add($data);
        if ($addId===false){
            self::getJoinInstance()->rollback();
            $dataFailure['msg']="抽奖失败，请联系管理员".self::getJoinInstance()->getError();
            return $dataFailure;
        }
        self::adjustPrizeNum($prizeId);
        self::getJoinInstance()->commit();
        $dataSuccess['prizeId']=$prizeId;
        $dataSuccess['msg']=$data['prizeNote'];
        return $dataSuccess;
    }



    //调整大转盘数量配置
    public static function adjustPrizeNum($id){
        $luckyM = self::getItemInstance();
        $prizeNum = $luckyM->where("id={$id}")->getField('prizeNum');
        if($prizeNum > 0) {
            $luckyM->where("id={$id}")->setDec("prizeNum");
        }
    }
}